/*
 * @Author: cl
 * @Description:
 * @Date: 2023-04-18 11:12:58
 * @LastEditTime: 2023-05-04 11:36:52
 * @FilePath: \jsnode\nestjs\naota\src\student\student.service.ts
 * @LastEditors: cl
 */
import { Injectable } from '@nestjs/common'
import { CreateStudentDto } from './dto/create-student.dto'
import { UpdateStudentDto } from './dto/update-student.dto'
import { Student } from './entities/student.entity'
import { Repository, Like } from 'typeorm'
import { InjectRepository } from '@nestjs/typeorm'
import { StuInfo } from './entities/stuInfo.entity'

@Injectable()
export class StudentService {
  constructor(
    @InjectRepository(Student) private readonly student: Repository<Student>,
    @InjectRepository(StuInfo) private readonly stuInfo: Repository<StuInfo>,
  ) {}

  //新增学生
  create(createStudentDto: CreateStudentDto) {
    const student = new Student()
    student.name = createStudentDto.name
    student.sex = createStudentDto.sex
    student.no = createStudentDto.no
    student.birth = createStudentDto.birth
    student.remark = createStudentDto.remark
    return this.student.save(student)
  }

  //学生列表
  async findAll(keyWord?) {
    const list = await this.student.find({
      where: {
        name: Like(`%${keyWord}%`),
      },
      // select: ['name', 'sex', 'no', 'birth', 'id'], //选择某些字段
      relations: ['stuInfo'],
    })
    return list
  }

  findOne(id: number) {
    return this.student.findOne({
      where: { id: id },
    })
  }

  update(id: number, updateStudentDto: UpdateStudentDto) {
    return this.student.update({ id: id }, updateStudentDto)
  }

  remove(id: number) {
    return this.student.delete({ id: id })
  }

  /*************** 学生信息 ***********************/
  //新建信息
  async addUserInfo(row: Student) {
    const stuInfo = new StuInfo()
    stuInfo.url = row.stuInfo.url
    stuInfo.address = row.stuInfo.address
    await this.stuInfo.save(stuInfo)
    row.stuInfo = stuInfo
    return this.student.update({ id: row.id }, row)
  }
  //更新信息
  async updateUserInfo(id: number, stuInfo: StuInfo) {
    return await this.stuInfo.update({ id: id }, stuInfo)
  }
}
